import re

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render,redirect
from django.views.decorators.csrf import csrf_exempt

from blocg_proj import settings
from blog_app.models import *
import  hashlib
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
import json
from django.core import serializers

# Create your views here.
SUCCESS = 0
FAILURE = 1
def index(request):
    return render(request, 'blog/index.html')

def register(request):
    user = None
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        phone = request.POST.get('phone')

        if username == None or password == None:
            return JsonResponse({'msg':'注册失败，用户名密码不能为空','status':FAILURE})
        #验证手机号 是否为空
        if phone == None:
            return JsonResponse({'msg': '注册失败，手机号不能为空', 'status': FAILURE})
        #验证用户是否存在
        user_valid  = check_valid(username,'username')
        phone_valid = check_valid(phone,'phone')
        if user_valid and phone_valid:
            new_user = User()
            new_user.username = username
            password = password.encode(encoding = "UTF-8")
            new_user.password = hashlib.md5(password).hexdigest()
            new_user.phone = phone
            #设置默认头像
            new_user.avatar = '/img/user_icon.jpg'
            try:
                new_user.save()
                return JsonResponse({'msg': '注册成功', 'status': SUCCESS})
            except Exception as err:
                print(err)
                return JsonResponse({'msg': '注册失败,请重试', 'status': FAILURE})
        else:
            return JsonResponse({'msg': '注册失败,用户名或手机号有误', 'status': FAILURE})


def login(request):
    #通过用户名查询
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 判断空
        if username == None or password == None or username == '' or password == '':
            return JsonResponse({'msg': '登陆失败,用户名和密码不能为空', 'status': FAILURE})
        password = password.encode(encoding="UTF-8")
        password = hashlib.md5(password).hexdigest()
        login_user = User.objects.filter(username=username, password=password)
        if login_user != None and len(login_user) > 0 :
            request.session['userinfo'] = login_user[0].userId
            #return HttpResponse(json.dumps({'msg': '登陆成功', 'status': SUCCESS},ensure_ascii=False),content_type="application/json,charset=utf-8")
            return JsonResponse({'msg': '登陆成功', 'status': SUCCESS},safe=False)
    return JsonResponse({'msg': '登陆失败，请检查用户名、密码', 'status': FAILURE})


def check_valid(data,type):
    """
    :param data: str
    :param type: str
    :return: json
    """
    if type == 'username':
        count = len(User.objects.filter(username=data))
        if count > 0:
            return False
    if type == 'phone':
        count = len(User.objects.filter(phone=data))
        valid_phone = re.search('^1[34578]\d{9}$',data)
        if count > 0 and valid_phone != None:
            return False
    return True
# 异步校验用户名
def check_username(request):
    valid = check_valid(request.GET.get('username'), 'username')
    return JsonResponse({'valid':valid})

# 异步校验手机号
def check_phone(request):
    valid = check_valid(request.GET.get('phone'), 'phone')
    return JsonResponse({'valid':valid})

def write_blog_page(request):
    return render(request,'blog/writeBlog.html')

def logout(request):
    request.COOKIES.clear()
    request.session.flush()
    return redirect('/')

def save_blog(request):
    #获取信息
    blog_title = request.POST.get('blogTitle')
    cover_image = request.POST.get('coverImage')
    blog_content = request.POST.get('blogContent')
    type_id = request.POST.get('typeId')
    tag_id = request.POST.get('tagId')

    # 非空判断
    if blog_title != None and blog_content != None:
        #保存
        blog = Blog()
        blog.blog_title = blog_title
        blog.blog_content = blog_content
        if cover_image:
            blog.cover_image = cover_image
        blog.type = BlogType.objects.get(type_id = type_id)
        blog.blog_status = 1
        blog.user = request.user_object
        try:
            blog.save()
            return redirect('/')
        except Exception as error:
            print(error)
            return render(request, 'blog/writeBlog.html', {'error': '创建失败请重试'})
    return render(request,'blog/writeBlog.html',{'error':'标题或内容不能为空'})
#保存markdown图片
def upload_md_img(request):

    request.FILES.get('editormd-image-file')   #markdown 编辑器上传图片

    return None
#上传图片
def upload_img(request):
    file = request.FILES.get('file')
    fname = '%spic/%s'%(settings.MEDIA_ROOT,file.name)
    try:
        with open(fname,'wb') as pic:
            for c in file.chunks():
                pic.write(c)
            return JsonResponse({'success':1,'message':'上传成功','url':file.name})
    except Exception as error:
        print(error)
        return JsonResponse({'success':0,'message':'上传失败'})



#分页查询
@csrf_exempt
def query_page(request):
    page_num = request.POST.get('pageNum')
    page_size = 5  #每页数据量
    blogs = Blog.objects.all().filter(blog_status=1).order_by('blog_id')[::-1]
    #获取分页对象
    paginator = Paginator(blogs, page_size)
    response = {}
    response['total'] = paginator.count   #数据总量
    try:
        blog_list = paginator.page(page_num)
        #response['blog_list'] = BlogSerializers(blog_list,many = True).data
        blog_list = list(blog_list)
        blog_data = []
        for blog in blog_list:
            info = {}
            info['blogId'] = blog.blog_id
            info['blogTitle'] = blog.blog_title
            info['userid'] = blog.user.userId
            info['typeId'] = blog.type.type_id
            info['blogStatus'] = blog.blog_status
            info['coverImage'] = blog.cover_image
            info['typeName'] = blog.type.type_name
            info['createTime'] = blog.create_time
            info['updateTime'] = blog.update_time
            info['username'] = blog.user.username
            blog_data.append(info)
        print(blog_data)
        # response['list'] = json.loads(serializers.serialize('json',{'list':blog_data}))
        response['list'] = blog_data
        num_pages = paginator.num_pages
        print(num_pages,page_num)
        if int(num_pages) >= int(page_num) + 1:
            response['nextPage'] = (int(page_num) + 1)
        else:
            response['nextPage'] = 0
    except EmptyPage:
        response['nextPage'] = 0
        response['list'] = []
    except Exception as error:
        print(error.__str__())

    print(response)
    return JsonResponse(response)


def blog_detail(request):
    blogid = request.GET.get('id')
    blog = Blog.objects.get(blog_id= blogid)
    return render(request,'blog/blogDetail.html',{'blog':blog})